from fastapi import APIRouter, HTTPException,Depends,Form
from fastapi.responses import JSONResponse
from sqlalchemy.orm import Session
from lisdemo.sql_app import crud
from lisdemo.sql_app.database  import get_db
from lisdemo.mygeotools.trans import trans
import time
from datetime import datetime
router = APIRouter()



@router.get("/")
async def read_items():
    return [{"name": "Item Foo"}, {"name": "item Bar"}]


@router.get("/{item_id}")
async def read_item(item_id: str):
    return {"name": "Fake Specific Item", "item_id": item_id}

@router.get("/allline/")
def read_user(db: Session = Depends(get_db),starttime:datetime=Form(...),endtime:datetime=Form(...)):
    db_point = crud.getall_point(db)
    for x in db_point:
        x.pointtime = time.mktime(x.pointtime.timetuple())
    allpoint = [i.to_geojson() for i in db_point]
    pan = trans.feature2gdf(allpoint)
    res = []
    user_id = pan['user_id'].unique()
    for index in user_id:
        point = pan[pan['user_id'] == index]['geometry'].apply(lambda x: list(x.coords[0]))
        path = point.values.tolist()
        # print(path)
        pointtime = pan[pan['user_id'] == index]['pointtime'].apply(float)
        # pointtime=pan[pan['user_id'] == index]['pointtime']
        timestamp = pointtime.values.tolist()
        # print(type(timestamp[0]))
        dict1 = {"vendor": int(index), "path": path, "timestamps": timestamp}
        res.append(dict1)
    if db_point is None:
        raise HTTPException(status_code=404, detail="User not found")
    return JSONResponse(res)

@router.put(
    "/{item_id}",
    tags=["custom"],
    responses={403: {"description": "Operation forbidden"}},
)
async def update_item(item_id: str):
    if item_id != "foo":
        raise HTTPException(status_code=403, detail="You can only update the item: foo")
    return {"item_id": item_id, "name": "The Fighters"}